import 'dart:async';
import 'dart:io';

import 'package:flutter_mqtt/src/mqtt_config.dart';
import 'package:flutter_mqtt/src/mqtt_helper.dart';

void main() async {
  // 初始化
  final mqttManager = MqttHelper(
    // server: 'broker.emqx.io',
    MqttConfig(
      server: 'broker.emqx.io',
      clientId: 'flutter_client_${DateTime.now().millisecondsSinceEpoch}',
      enableAutoReconnect: true,
    ),
  );
  mqttManager.initialize();
  mqttManager.connectionStream.listen((it) {
    if (it) {
      print("连接成功");
    } else {
      print("连接失败");
    }
  });
  mqttManager.errorStream.listen((it) {
    print("error: $it");
  });
  mqttManager.messageStream.listen((it) {
    print("Received message on : $it");
  });
  // 连接服务器
  await mqttManager.connect();
  // 订阅主题
  mqttManager.subscribe('vk/bx40/863758060034658/tidy/');

  // 阻止程序退出的关键代码
  // await Future.delayed(Duration(days: 365)); // 让程序等待一个超长延迟
// 使用信号监听保持程序运行（支持Ctrl+C退出）
  final completer = Completer<void>();
  ProcessSignal.sigint.watch().listen((_) => completer.complete());
  await completer.future;

  // 断开连接后退出
  mqttManager.disconnect();
  await Future.delayed(Duration(seconds: 4));
}
